package com.angeho.filter;




import lombok.extern.log4j.Log4j2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;


@Component
@Log4j2
public class HttpHeaderFilter extends GenericFilterBean {
    Logger logger= LoggerFactory.getLogger("HttpHeaderFilter");
    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @Value("${com.bonatone.token-excluded-path}")
    String  excludedPath;

    /**
     * 当请求路径符合排除路径时，直接放行
     * @param servlertPath 请求的路径
     * @return 是否直接放行
     */
    protected boolean isPass(String servlertPath) {
        String[] excludedPaths = excludedPath.split(",");
        for (String pattern : excludedPaths) {
            pattern = pattern.trim();
            if (pattern.endsWith("/**")) {
                // 匹配任意多级路径
                if (servlertPath.startsWith(pattern.substring(0, pattern.length() - 3))) {
                    return true;
                }
            } else if (pattern.endsWith("/*")) {
                // 匹配二级路径
                String basePath = pattern.substring(0, pattern.length() - 2);
                String lastPath = servlertPath.substring(basePath.length());
                if(lastPath.startsWith("/")) {
                    lastPath=lastPath.substring(1);
                }
                if (servlertPath.startsWith(basePath)
                    && lastPath.indexOf('/') == -1) {
                    return true;
                }
            } else {
                // 精确匹配
                if (servlertPath.equals(pattern)) {
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
